package com.bangdream.michelia.view.fragment.main.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.application.MainApplication;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.DomainBean;
import com.bangdream.michelia.entity.MessageBean;
import com.bangdream.michelia.entity.RxEventBean;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.tool.NoScrollViewPager;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.utils.RxBus;
import com.bangdream.michelia.utils.SPUtils;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.currency.MainActivity;
import com.bangdream.michelia.view.activity.currency.OnMainActivityOperationListener;
import com.bangdream.michelia.view.activity.my.MyMessage;
import com.bangdream.michelia.view.adapter.PopListAdapter;
import com.bangdream.michelia.view.fragment.currency.BaseFragment;
import com.bangdream.michelia.view.fragment.main.task.TaskExaminationList;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MainHome extends BaseFragment implements View.OnClickListener,ViewPager.OnPageChangeListener{
    private View view;
    private View statusBarLayout;
    private TextView[] btnTvs = new TextView[3];
    private NoScrollViewPager mViewPage;
    private FragmentPagerAdapter mAdapter;
    //选项卡被选中和未选中时的字体颜色
    private int onTextColor,offTextColor;
    //viewpage的线条指示器
    private RelativeLayout indicatorView;
    //记录移动的开始位置 初始0
    private int previousPosition = 0;
    //屏幕的宽度
    private int screenWidth;
    //选择类型
    private TextView btnType;
    private RelativeLayout btnMessage;
    private ImageView btnSearch;
    private TextView tvNewNumber;

    private OnMainActivityOperationListener onMainActivityOperationListener;

    private PopupWindow mPop;
    LinearLayout ll_pop;
    RecyclerView pop_list;
    PopListAdapter popListAdapter;


    public OnMainActivityOperationListener getOnMainActivityOperationListener() {
        return onMainActivityOperationListener;
    }

    public void setOnMainActivityOperationListener(OnMainActivityOperationListener onMainActivityOperationListener) {
        this.onMainActivityOperationListener = onMainActivityOperationListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_item_home,container,false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        setListener();
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    private void setListener() {
        mViewPage.addOnPageChangeListener(this);
        btnType.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        btnMessage.setOnClickListener(this);

        for(TextView textView:btnTvs){
            textView.setOnClickListener(this);
        }
    }

    private void initView() {
        screenWidth = MainActivity.screenWidth;
        btnMessage = view.findViewById(R.id.btnMessage);
        btnSearch = view.findViewById(R.id.btnSearch);
        btnType = view.findViewById(R.id.btnType);
        tvNewNumber = view.findViewById(R.id.tvNewApprNumber);
        statusBarLayout = view.findViewById(R.id.statusBarLayout);
        ViewGroup.LayoutParams layoutParams = statusBarLayout.getLayoutParams();
        layoutParams.height = MainActivity.statusBarHeight;
        statusBarLayout.setLayoutParams(layoutParams);
        onTextColor = ContextCompat.getColor(mApp,R.color.common_red);
        offTextColor = ContextCompat.getColor(mApp,R.color.black_text);
        indicatorView = view.findViewById(R.id.indicatorView);
        btnTvs[0] = view.findViewById(R.id.btnTv1);
//        btnTvs[1] = view.findViewById(R.id.btnTv2);
        btnTvs[1] = view.findViewById(R.id.btnTv3);
        btnTvs[2] = view.findViewById(R.id.btnTv4);
        mViewPage = view.findViewById(R.id.mViewPage);
        mAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                switch (position){
                    case 0:
                        return new HomeLearningCenter();
                    case 1:
                        return new EliteLecturerList();
                    case 2:
                        final Bundle bundle = new Bundle();
                        bundle.putString("type","1");
                        TaskExaminationList fragment = new TaskExaminationList();
                        fragment.setArguments(bundle);
                        return fragment;

//                    case 3:
//                        return new SpecialCurriculumList();
                    default:
                        return null;
                }
            }

            @Override
            public int getCount() {
                return btnTvs.length;
            }
        };
        mViewPage.setAdapter(mAdapter);
        //缓存viewpage中的所有页面 不会滑动到第三页再返回第一页需要重新加载第一页
        mViewPage.setOffscreenPageLimit(mAdapter.getCount());

        btnType.setText((String)SPUtils.get(getActivity(),"domainName","白玉兰在线"));
        initQQPop();
        getDomainList();
        getUserMsg();
    }


    /**
     * 获取所有机构
     */
    private void getDomainList() {
        Map map = new HashMap();
        map.put("userId", AppCurrentUser.getInstance().getUserInfo().getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(map));
        String stTokent = AppCurrentUser.getInstance().getToken();

        Disposable subscribe = RetroFactory.getInstance().getDomain(stTokent, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseEntity<List<DomainBean>>>() {
                    @Override
                    public void accept(BaseEntity<List<DomainBean>> beans) throws Exception {
                        popListAdapter.setNewData(beans.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                    }
                });
    }
    /**
     * 获取用户消息
     */
    private void getUserMsg() {
        Map map = new HashMap();
        map.put("userId", AppCurrentUser.getInstance().getUserInfo().getId());
        map.put("readFlag","0");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(map));
        String stTokent = AppCurrentUser.getInstance().getToken();
        Disposable subscribe = RetroFactory.getInstance().getStationUserMessageList(stTokent, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseEntity<List<MessageBean>>>() {
                    @Override
                    public void accept(@NonNull BaseEntity<List<MessageBean>> messageBeanBaseEntity) throws Exception {
                        if(messageBeanBaseEntity!=null){
                            if(messageBeanBaseEntity.getCntData()==0)
                                tvNewNumber.setVisibility(View.GONE);
                            else
                                tvNewNumber.setVisibility(View.VISIBLE);
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                    }
                });
    }

    private void initQQPop() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_right_pop, null);
        mPop = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPop.setAnimationStyle(R.style.RightPopAnim);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        ll_pop = view.findViewById(R.id.ll_pop);
        pop_list = view.findViewById(R.id.pop_list);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        pop_list.setLayoutManager(linearLayoutManager);
        popListAdapter = new PopListAdapter(R.layout.pop_text);
        pop_list.setAdapter(popListAdapter);

        popListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mPop.dismiss();
                String code = popListAdapter.getData().get(position).getCode();
                String name = popListAdapter.getData().get(position).getName();
                btnType.setText(name);
                SPUtils.put(mApp,"doMain",code);
                SPUtils.put(mApp,"domainName",name);

                if(!oldDomain.equals(code)){
                    MainApplication.getInstance().setIsChangeDomain(true);
                    RxEventBean bean = new RxEventBean();
                    bean.setCode(0x02);
                    RxBus.getInstance().post(bean);
                }
            }
        });
    }
    String oldDomain;
    private void setChooseType(){
        oldDomain = (String) SPUtils.get(mApp, "doMain", "inesa");
        popListAdapter.setDefSelect(oldDomain);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnTv1:
                mViewPage.setCurrentItem(0);
                break;
//            case R.id.btnTv2:
//                mViewPage.setCurrentItem(1);
//                break;
            case R.id.btnTv3:
                mViewPage.setCurrentItem(1);
                break;
            case R.id.btnTv4:
                mViewPage.setCurrentItem(2);
                break;
            case R.id.btnType:
                mPop.showAsDropDown(btnType, 0, 0);
                setChooseType();
                break;

            case R.id.btnMessage:
                startActivity(new Intent(getActivity(), MyMessage.class));
                break;
            default:break;
        }
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //线条指示器移动
        TranslateAnimation ani = new TranslateAnimation(
                previousPosition * screenWidth/3,
                position * screenWidth/3, 0, 0);
        ani.setDuration(200);
        ani.setFillAfter(true);
        ani.setInterpolator(new AccelerateDecelerateInterpolator());
        //播放动画
        indicatorView.startAnimation(ani);
        //将这一次的位置保存起来，作为下一次移动的起始位置
        previousPosition = position;


        for(int i = 0;i<btnTvs.length;i++){
            if(i==position){
                btnTvs[i].setTextColor(onTextColor);
            }
            else {
                btnTvs[i].setTextColor(offTextColor);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
